const createError = require('http-errors');
const express = require('express');
const path = require('path');
const logger = require('morgan');
//log4js
const logger4 = require("./src/common/logger")
//引用ejs
const ejs = require('ejs')

//引用session
const session = require("express-session");
const cookieParser = require('cookie-parser');
const cors = require('cors');

// 视图路由列表
const indexRouter = require('./routes/index');
// const usersRouter = require('./routes/users');
const usersControllerRouter = require('./src/controller/user-controller');
const userLoginRouter = require('./src/controller/action-login');
const HomeRouter = require('./src/controller/home-controller');
const AlbumRouter = require('./src/controller/album-controller');


const app = express();

// view engine setup
//配置模板引擎视图的目录
app.set('views', path.join(__dirname, 'views'));
//启动视图引擎，并指定模板文件文件类型：html
app.set('view engine', 'html');
//模板类型指定为html
app.engine('html', ejs.__express)

app.use(cors({
    origin: ["http://127.0.0.1", "http://localhost", "http://127.0.0.1:3000", "http://localhost:3000"],
    credentials: true
}));
// 设置session
app.use(session({
    secret: "Just do it !",		          //设置签名秘钥  内容可以任意填写
    cookie: {maxAge: 30 * 3600 * 1000},   //设置cookie的过期时间，例：80s后session和相应的cookie失效过期
    resave: true,			              //强制保存，如果session没有被修改也要重新保存
    saveUninitialized: false              //如果原先没有session那么久设置，否则不设置
}))

// const accessLog = fs.createWriteStream('../access.log', {flags : 'a'});
// const errorLog = fs.createWriteStream('../error.log', {flags : 'a'});
// morgan ----- log
app.use(logger('dev')); //打印到控制台
// app.use(logger('combined', {stream : accessLog}));      //打印到log日志
// log4js
// app.use(require('log4js').connectLogger(logger4, { level: config.debug ? 'DEBUG' : 'ERROR' }));

app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
//设置静态目录
app.use(express.static(path.join(__dirname, 'public')));

/**
 * 登录拦截器，必须放在静态资源声明之后、路由导航之前

app.use(function (req, res, next) {
    const {url, body, params, query, path, originalUrl} = req
    console.log("拦截当前路由originalUrl:", originalUrl)
    const {session: {user}} = req
    console.log("session.user:", user)
    // res.header("Access-Control-Allow-Origin", "http://localhost:3000");
    res.header("Access-Control-Allow-Credentials", "true");
    // 获取浏览器中当前访问的nodejs路由地址
    if (originalUrl === "/action/login.html") { //通过判断控制用户登录后不能访问登录页面；
        console.log("-----------1:用户登录页面放行--------")
    } else if (originalUrl === "/action/login.do"){
        console.log("-----------2:用户登录操作放行--------")
    } else if (!user){
        console.log("-----------3:用户未登录，无session--------")
        res.redirect(302,"/action/login.html")
    } else {
        console.log("-----------4:用户已登录--------")
    }
    next()
});
 */

// 视图路由
app.use('/', indexRouter);
// app.use('/users', usersRouter);
app.use('/users', usersControllerRouter);
// app.use('/home', HomeRouter,AlbumRouter);

/**
 * 设置跨域设置
 */
// app.all("*",(req,res,next)=>{
//   res.header("Access-Control-Allow-Origin", "*");
//   res.header("Access-Control-Allow-Headers", "X-Requested-With");
//   res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
//   res.header("X-Powered-By", ' 3.2.1')
//   res.header("Content-Type", "application/json;charset=utf-8");
//   next()
// })


module.exports = app;
